#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<string>
#include "InetAddr.hpp"
#include "Logger.hpp"
#include "Common.hpp"

void Demand(const std::string&args)
{
    std::cout<<"请输入："<<args<<" IP "<<"端口号"<<std::endl;
}

int main(int argc,char*argv[])
{
    if(argc!=3)
    {
        Demand(argv[0]);
        exit(1);
    }
    std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
    {
        LOG(LogLevel::FATAL) << "socket创建失败";
        exit(SOCK_CREATE_ERR);
    }
    LOG(LogLevel::INFO) << "socket创建成功";
    InetAddr server(serverport,serverip);
    int n=connect(fd,server.Addr(),server.Len());
    if(n<0)
    {
        std::cerr<<"连接服务器失败"<<std::endl;
        exit(SOCK_CONNECT_ERR);
    }
    std::cout << "connect " << server.ToString() << " 成功" << std::endl;
    while(true)
    {
        std::cout<<"请输入：";
        std::string line;
        std::getline(std::cin,line);
        ssize_t m=write(fd,line.c_str(),line.size());
        if(n>=0)
        {
            char buffer[1024];
            ssize_t x=read(fd,buffer,sizeof(buffer)-1);
            if(x>0)
            {
                buffer[x]=0;
                std::cout<<buffer<<std::endl;
            }
        }
    }
    return 0;
}